package com.itheima.reggie.exception;


import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String[] str = ex.getMessage().split(" ");
            System.out.println(ex.getMessage());
            return R.error("用户"+str[2]+"已存在！");
        }
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHanlder(CustomException ex){
        return R.error(ex.getMessage());
    }
}
